package com.ztools.common.util.common;

import cn.hutool.http.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @Author: seeTools
 * @Date: 2023/4/25  8:29
 * @Version 1.0
 */
@Component
public class DingDingUtils {

    private static final String COMPANY = "小钉钉";
    private static final String DINGDING_WEBHOOK = "https://oapi.dingtalk.com/robot/send?access_token=3986a6ed62d86c7e78741fe83e499367b76fe6624c73564952ec4121391e5391";
    private static final String DINGDING_SECRET = "SECaf5c193163941f21c3edfb793edf4e5be96f858cea7a03297b1af05461f19c24";
    private static String env;

    /**
     * 发文本消息
     *
     * @param message message
     */
    public static void sendSimpleMessage(String message) {
        Long timestamp = System.currentTimeMillis();
        String sign = null;
        try {
            sign = getSign(timestamp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Gson gson = new Gson();
        String ddUrl = DINGDING_WEBHOOK + "&timestamp=" + timestamp + "&sign=" + sign;
        JsonObject params = new JsonObject();
        JsonObject text = new JsonObject();
        params.addProperty("msgtype", "text");
        text.addProperty("content", message);
        params.add("text", text);
        HttpUtil.post(ddUrl, gson.toJson(params));

    }

    private static String getSign(Long timestamp) throws Exception {
        String stringToSign = timestamp + "\n" + DINGDING_SECRET;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(DINGDING_SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = new byte[0];
        signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        return URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
    }
}
